package com.zz.common.exception;

import com.zz.common.base.enums.IBaseExceptionEnum;
import org.apache.commons.lang3.StringUtils;

/**
 * @author zl
 * @version 1.0
 *
 * 异常工厂：
 */
public class ExceptionFactory {

    public static BaseException createBaseException(IBaseExceptionEnum baseExceptionEnum, String... params) {
        String msg = messageFormat(baseExceptionEnum.getMessage(), params);
        return new BaseException(baseExceptionEnum.getCode(), msg);
    }

    private static String messageFormat(String message, String... params) {
        //动态参数列表不为空时，替换message中的{0}、{1}……{n}
        if (params != null && params.length > 0) {
            String param = null;
            String replaceKey = null;
            for (int i = 0; i < params.length; i++) {
                replaceKey = "{" + i + "}";
                param = params[i];
                if (StringUtils.isBlank(param)) {
                    param = "";
                }
                message = message.replace(replaceKey, param);
            }
        }

        return message;
    }

}
